package com.basis.handler;

import com.basis.handler.service.DataImportInterface;
import com.basis.handler.service.DataImportService;
import com.basis.utils.BaseServletHandler;
import com.mes.data.EmesDataImport;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@SuppressWarnings("unchecked")
public class DataImportHandler extends BaseServletHandler {
	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected JSONObject service(HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		try {
			OBContext.setAdminMode();
			String code = request.getParameter("code");
			
			request.setCharacterEncoding("utf-8");
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置 缓存的大小，当上传文件的容量超过该缓存时，直接放到 暂时存储室
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			// 可以上传多个文件
			List<FileItem> listItem = (List<FileItem>) upload.parseRequest(request);
			
			OBQuery<EmesDataImport> createQuery = OBDal.getInstance().createQuery(EmesDataImport.class, "code = :code");
			createQuery.setNamedParameter("code", code);
			EmesDataImport dataImport = createQuery.uniqueResult();

			DataImportInterface service = null;
			if (dataImport != null && dataImport.getActionHandler() != null && !"".equals(dataImport.getActionHandler())) {
				service = (DataImportInterface) Class.forName(dataImport.getActionHandler()).newInstance();
			} else {
				service = new DataImportService();
			}
			service.setEmesDataImport(dataImport);
			
			for (FileItem item : listItem) {
				if (!item.isFormField()) {
					String name = item.getName();
					InputStream is = item.getInputStream(); // 文件流
					result = service.importData(is, name, request);
					break;
				}
			}
			OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
			e.printStackTrace();
			OBDal.getInstance().rollbackAndClose();
			logger.error("数据异常：" + e.getMessage(), e);
			try {
				result.put("result", false);
				
				String msg = e.getMessage();
				if (e.getCause() != null) {
					if (e.getCause().getCause() != null) {
						msg = "，" + e.getCause().getCause().getMessage().split("ORA-06512")[0];
					} else {
						msg = "，" + e.getCause().getMessage().split("ORA-06512")[0];
					}
				}
				result.put("msg", "数据导入异常" + msg);
			} catch (Exception e1) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return result;
	}
}
